<template>
  <div class="MkAddActivity">
    <mk-breadcrumb :breadcrumb-data="breadcrumbData"></mk-breadcrumb>
    <el-scrollbar :wrapStyle="[{maxHeight:(bodyHeight-fixedHeightSmall)+'px'}]">
    <div class="content-box">
        <!-- 写文章 -->
        <div class="add-article-content-box">
          <el-form :model="articleDetailData" ref="articleForm" label-position="right" label-width="96px"
                   class="top-form" :rules="submitFormRules">
            <el-form-item label="活动标题" prop="title">
              <el-input v-model="articleDetailData.title" placeholder="请输入活动标题（必填）" :minlength='5' :maxlength='30'></el-input>
            </el-form-item>
            <el-form-item label="活动地点">
              <el-col :span="11">
                <el-form-item prop="provinceId" style="width:100%">
                  <el-select v-model.number="articleDetailData.provinceId" placeholder="请选择活动省份（必选）" @change="changeProvince">
                    <el-option v-for="item in provinceData" :value = 'item.id' :label = 'item.name' :key = 'item.id'></el-option>
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col class="line" :span="2" align="center">-</el-col>
              <el-col :span="11">
                <el-form-item prop="cityId" style="width:100%">
                  <el-select v-model.number="articleDetailData.cityId" placeholder="请选择活动城市（必选）">
                    <el-option v-for="item in cityData" :value = 'item.id' :label = 'item.name' :key = 'item.id'></el-option>
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="24" style="margin-top:20px;">
                <el-form-item prop="detailAddress" style="width:100%">
                  <el-input placeholder="请输入详细地址（必填）" :maxlength='100' @change="changeField('articleDetailData','articleForm','detailAddress')" v-model="articleDetailData.detailAddress"></el-input>
                </el-form-item>
              </el-col>
              <!--<el-input v-model="articleDetailData.source" placeholder="请输入活动地点（必填）" :maxlength='8'></el-input>-->
            </el-form-item>
            <el-form-item label="活动时间">
              <el-col :span="11">
                <el-form-item prop="activityStartDate_" style="width:100%">
                  <el-date-picker type="datetime" placeholder="请选择活动开始时间（必选）" format="yyyy-MM-dd HH:mm" v-model.date="articleDetailData.activityStartDate_" style="width: 100%;"></el-date-picker>
                </el-form-item>
              </el-col>
              <el-col class="line" :span="2" align="center">至</el-col>
              <el-col :span="11">
                <el-form-item prop="activityEndDate_" style="width:100%">
                  <el-date-picker type="datetime" placeholder="请选择活动结束时间（必选）"  format="yyyy-MM-dd HH:mm" v-model.date="articleDetailData.activityEndDate_" style="width: 100%;"></el-date-picker>
                </el-form-item>
              </el-col>

            </el-form-item>

            <el-form-item label="活动海报" prop="imageIds">
              <el-upload
                class="avatar-uploader"
                accept=".jpeg, .jpg, .png, .gif"
                :action="'/upload/image.json'"
                :show-file-list="false"
                :data="{'width':800,'height':800}"
                :on-success="handleSuccess"
                :before-upload="beforeCoverUpload"
                name="image">
                <img v-if="imageUrl" :src="imageUrl" class="avatar">
                <i v-else class="el-icon-plus avatar-uploader-icon"></i>
              </el-upload>
              <p style="color:#83a0a5;font-size:14px;">建议上传800*800规格的图片</p>
            </el-form-item>
            <el-form-item label="主办方" prop='sponsor'>
              <el-input v-model="articleDetailData.sponsor" placeholder="请输入主办方" :maxlength='100'></el-input>
            </el-form-item>
            <el-form-item label="活动内容" prop='content' class="ckeditor-content-size">
              <mk-ckeditor v-model="articleDetailData.content" class="article-editor"></mk-ckeditor>
              <p style="color:#83a0a5;font-size:14px;text-align: left;">建议活动内容中的图片宽度不超过800</p>
            </el-form-item>

            <el-form-item label="活动人数" prop="limitPeopleAmount">
              <el-input v-model="articleDetailData.limitPeopleAmount" placeholder="请输入活动人数" style="width:350px;"></el-input>
              <span style="position:absolute;top:0;left:370px;color:#b6c2c9">0表示不限制</span>
            </el-form-item>

            <!--<template v-if="!onlyPub">-->
              <div style = 'position:relative;'>
                <el-form-item label="报名时间" prop="enterType">
                  <el-radio-group v-model="articleDetailData.enterType">
                    <el-radio label="Default">默认活动结束前</el-radio>
                    <el-radio label="Appoint">指定时间</el-radio>
                  </el-radio-group>
                </el-form-item>

                <template v-if="articleDetailData.enterType === 'Appoint'" >
                  <el-form-item label="" prop="enterStartDate_" style="width:300px;position:absolute;top:0px;left:240px;">
                    <el-date-picker  v-model.date="articleDetailData.enterStartDate_"  type="datetime" format="yyyy-MM-dd HH:mm" placeholder="请选择报名开始时间（必选）">
                    </el-date-picker>
                  </el-form-item>
                  <span style="width:100px;position:absolute;top:10px;left:550px;font-size:14px;">至</span>
                  <el-form-item label="" prop="enterEndDate_" style="width:300px;position:absolute;top:0px;left:480px;">
                    <el-date-picker  v-model.date="articleDetailData.enterEndDate_" type="datetime" format="yyyy-MM-dd HH:mm" placeholder="请选择报名结束时间（必选）">
                    </el-date-picker>
                  </el-form-item>
                </template>
              </div>

            <div v-if="articleDetailData.siteSelect.length === 0" style="margin-bottom:20px;">
              <div style="color: #81939e;display: inline-block;width:76px;font-size:14px;text-align: right;padding-right:20px;">所属站点</div>
              <div class='addNode' @click='addApproval' style="font-size:14px;">
                <i class='el-icon-plus' ></i> 添加站点
                </div>
            </div>

            <template v-else>
              <template v-for='(item,index) in articleDetailData.siteSelect'>
                <el-form-item :label='index==0?"所属站点":""' style=''>
                  <el-col :span="22">
                    <el-form-item style='width:100%;' :prop="'siteSelect.'+index+'.siteIdArr'" :rules="{ required: true, type:'array',message: '请选择站点'}" :key='"siteIdArr_"+item.key'>
                      <el-cascader
                        :props="options"
                        :options="siteArr"
                        multiple
                        v-model="item.siteIdArr"
                        placeholder="请选择站点（必选）">
                      </el-cascader>
                    </el-form-item>
                  </el-col>
                  <el-col :span='2' class='textAlignCenter'>
                    <i class='el-icon-error cursorPointer' style='color:#fb5f5f;font-size:16px;' @click='deleteApprovalInput(item)'></i>
                  </el-col>
                </el-form-item>
              </template>

              <div  style="margin-bottom:20px;">
                <div style="color: #81939e;visibility:hidden;display: inline-block;width:76px;font-size:14px;text-align: right;padding-right:20px;">所属站点</div>
                <div class='addNode' @click='addApproval' style="font-size:14px;">
                  <i class='el-icon-plus' ></i> 添加站点
                  </div>
              </div>
            </template>

          </el-form>
        </div>

        <div class="ensure-save-box" v-if="!activityId || (activityId && dataSource == 'OPERATION' )">
            <el-button class="btnStyle color1" type="primary"  v-loading.fullscreen.lock="fullscreenLoading"
                       @click="pubActivity('articleForm')" v-if="!activityId || (activityId && dataSource == 'OPERATION' )">发布
            </el-button>
            <el-button class="btnStyle color2" type="primary"  v-loading.fullscreen.lock="fullscreenLoading"
                       @click="saveActivity('articleForm')" v-if="!activityId">保存
            </el-button>
        </div>

    </div>
    </el-scrollbar>
  </div>

</template>

<script>
  import MkBreadcrumb from '../../../components/MkBreadcrumb.vue'
  import {mapState} from 'vuex'
  import activityService from '../../../services/activity'
  export default {
    name: 'MkAddActivity',
    props: ['title', 'id'],
    components: {
      MkBreadcrumb
    },
    methods: {
      changeField(form,formName, field) {
        this[form][field] = (this[form][field] + '').trim();
        this.$refs[formName].validateField(field);
      },
      beforeCoverUpload(file) {
        let fileName = file.name;
        let suffix = fileName.substr(file.name.lastIndexOf("."), fileName.length).toLowerCase();
        let support = false;
        for (let i = 0; i < this.supportFile.length; i++) {
          if (suffix === this.supportFile[i]) {
            support = true;
            break;
          }
        }
        if (!support) {
          this.$message.warning('只能上传图片格式的文件');
          return support;
        }
        const isLt5M = file.size / 1024 / 1024 < 5;
        if (!isLt5M) {
          this.$message.error('图片大小不能超过 5MB!');
        }
        return isLt5M;
      },
      handleSuccess(res, file) {
        this.imageUrl = URL.createObjectURL(file.raw);
        this.articleDetailData.imageIds = res.data.fileId;
        this.changeField('articleDetailData','articleForm', 'imageIds')
      },
      positionChange(value) {
        let labels = this.positionCheckList;
        let positions = '';
        for (let i = 0; i < labels.length; i++) {
          switch (labels[i]) {
            case '热点资讯' :
              positions += 'COMMUNITY_HEADLINES';
              break;
            case '社区公告' :
              positions += 'COMMUNITY_ANNOUNCEMENT';
              break;
            case '活动入口':
              positions += 'ARTICLE_FOR_ACTIVE';
          }
          positions += ',';
        }
        positions = positions.substr(0, positions.length - 1);
        this.articleDetailData.positions = positions;
      },
      pubActivity(formName) {
        this.$refs[formName].validate((valid) => {
          if (valid) {
            let param = {};
            let siteIdsArr = [];
            let articleDetailData = this.articleDetailData;
            articleDetailData.published = true;
            articleDetailData.activityEndDate = new Date(articleDetailData.activityEndDate_).pattern('yyyy-MM-dd HH:mm');
            articleDetailData.activityStartDate = new Date(articleDetailData.activityStartDate_).pattern('yyyy-MM-dd HH:mm');

            if(articleDetailData.enterType == 'Appoint'){
              articleDetailData.enterStartDate = new Date(articleDetailData.enterStartDate_).pattern('yyyy-MM-dd HH:mm');
              articleDetailData.enterEndDate = new Date(articleDetailData.enterEndDate_).pattern('yyyy-MM-dd HH:mm');
            }else{
              articleDetailData.enterStartDate = '';
              articleDetailData.enterEndDate = '';
            }
            if(articleDetailData.siteSelect.length == 0){
              this.$message.warning('请选择所属站点');
              return;
            }
            for(let i=0; i<articleDetailData.siteSelect.length;i++) {
              let item = articleDetailData.siteSelect[i];
              let siteId = item.siteIdArr[item.siteIdArr.length - 1];
              if(siteIdsArr.indexOf(siteId) == -1) {
                siteIdsArr.push(siteId);
              }
            }
            if(articleDetailData.siteSelect.length !== siteIdsArr.length) {
              this.$message.warning('选择的站点有重复');
              return;
            }
            articleDetailData.siteIds = siteIdsArr.join(',');

            for(let i in articleDetailData) {
              if(i!=='siteSelect' && i!== 'enterType'  && i!=='enterEndDate_'&& i!=='enterStartDate_'&& i!=='activityEndDate_'&& i!=='activityStartDate_' && i!=='id') {
                param[i] = articleDetailData[i];
              }
            }

            if (!this.isSubmit) {
              this.isSubmit = true;
              this.fullscreenLoading = true;
              if (this.activityId) {
                param.id = articleDetailData.id;
               activityService.editActivityServer(param,  (data) =>{
                  this.$message({
                    message:'发布成功',
                    type:'success',
                    duration:1000
                  });
                  setTimeout(()=>{
                    this.$router.push({path: '/operationMgt/activityMgt'});
                  },1000)
                },(data)=>{
                  this.isSubmit = false;
                  this.fullscreenLoading = false;
                })
              }else{
                activityService.addActivityServer(param,  (data) =>{
                  this.$message({
                    message:'发布成功',
                    type:'success',
                    duration:1000
                  });
                  setTimeout(()=>{
                    this.$router.push({path: '/operationMgt/activityMgt'});
                  },1000)
                },(data)=>{
                  this.isSubmit = false;
                  this.fullscreenLoading = false;
                })
              }
            }
          }
        })


      },
      saveActivity(formName) {
        this.$refs[formName].validate((valid) => {
          if (valid) {
            let param = {};
            let siteIdsArr = [];
            let articleDetailData = this.articleDetailData;
            articleDetailData.published = false;
            articleDetailData.activityEndDate = new Date(articleDetailData.activityEndDate_).pattern('yyyy-MM-dd HH:mm');
            articleDetailData.activityStartDate = new Date(articleDetailData.activityStartDate_).pattern('yyyy-MM-dd HH:mm');

            if(articleDetailData.enterType == 'Appoint'){
              articleDetailData.enterStartDate = new Date(articleDetailData.enterStartDate_).pattern('yyyy-MM-dd HH:mm');
              articleDetailData.enterEndDate = new Date(articleDetailData.enterEndDate_).pattern('yyyy-MM-dd HH:mm');
            }else{
              articleDetailData.enterStartDate = '';
              articleDetailData.enterEndDate = '';
            }
            if(articleDetailData.siteSelect.length == 0){
              this.$message.warning('请选择所属站点');
              return;
            }
            for(let i=0; i<articleDetailData.siteSelect.length;i++) {
              let item = articleDetailData.siteSelect[i];
              let siteId = item.siteIdArr[item.siteIdArr.length - 1];
              if(siteIdsArr.indexOf(siteId) == -1) {
                siteIdsArr.push(siteId);
              }
            }
            if(articleDetailData.siteSelect.length !== siteIdsArr.length) {
              this.$message.warning('选择的站点有重复');
              return;
            }
            articleDetailData.siteIds = siteIdsArr.join(',');

            for(let i in articleDetailData) {
              if(i!=='siteSelect' && i!== 'enterType'  && i!=='enterEndDate_'&& i!=='enterStartDate_'&& i!=='activityEndDate_'&& i!=='activityStartDate_' && i!=='id') {
                param[i] = articleDetailData[i];
              }
            }
            if (!this.isSubmit) {
              this.isSubmit = true;
              this.fullscreenLoading = true;
              activityService.addActivityServer(param,  (data)=>{
                this.$message({
                  message:'保存成功',
                  type:'success',
                  duration:1000
                });
                setTimeout(()=>{
                  this.$router.push({path: '/operationMgt/activityMgt'});
                },1000)
              },(data)=>{
                this.isSubmit = false;
                this.fullscreenLoading = false;
              })
            }

          }
        })
      },
      changeProvince(provinceId) {
        activityService.loadCitySelectServer({id:provinceId,fields:'id,name'},data => {
            this.cityData = data.data;
            if(this.activityId) {
                if(this.isFirstEnter) {
                  this.isFirstEnter = false;
                }else{
                  this.articleDetailData.cityId = '';
                }
            }else{
              this.articleDetailData.cityId = '';
            }

        })
      },
      loadProvinceData() {
        activityService.loadProvinceSelectServer({fields:'id,name'},data => {
          this.provinceData = data.data;
        })
      },
      deleteApprovalInput(item) {
        var index = this.articleDetailData.siteSelect.indexOf(item)
        if (index !== -1) {
          this.articleDetailData.siteSelect.splice(index, 1);
        }
      },
      addApproval() {
        this.articleDetailData.siteSelect.push({
          siteIdArr: [],
          key: Date.now()
        })
      },
    },
    computed: mapState({
      bodyHeight: state => state.global.bodyHeight,
      fixedHeightSmall: state => state.global.fixedHeightSmall,
      siteArr: state => {
        let arr = [];
        let data = state.site.siteTree;
        if(data.children){
          for(var i=0;i<data.children.length;i++) {
            let item = data.children[i];
            if(item.children && item.children.length>0) {
              arr.push(item);
            }
          }
        }
        return arr;
      }
    }),
    mounted: function () {
      this.activityId = this.$route.params.id;
      let activityId = this.activityId;
      let articleDetailData = this.articleDetailData;
      this.loadProvinceData();
      if(activityId){
        activityService.loadActivityDetailServer({id:activityId},data => {
          let detail = data.data;
          this.dataSource = detail.dataSource;
          articleDetailData.id = detail.id;
          articleDetailData.title = detail.title;
          articleDetailData.activityStartDate_ = new Date(detail.activityStartDate);
          articleDetailData.activityEndDate_ = new Date(detail.activityEndDate);
          articleDetailData.imageIds = detail.posters[0].fileId;
          this.imageUrl = detail.posters[0].accessUrl;
          articleDetailData.sponsor = detail.sponsor;
          articleDetailData.content = detail.content;
          articleDetailData.limitPeopleAmount = detail.limitPeopleAmount;

          articleDetailData.detailAddress = detail.detailAddress;
          articleDetailData.provinceId = detail.provinceId;
          articleDetailData.cityId = detail.cityId;
          articleDetailData.enterType = detail.enterType;
          for(let i=0;i<detail.sites.length;i++) {
            articleDetailData.siteSelect.push({
              key: Date.now(),
              siteIdArr: detail.sites[i],
            })
          }
          if(detail.enterType == 'Appoint') {
            articleDetailData.enterStartDate_ = new Date(detail.enterStartDate);
            articleDetailData.enterEndDate_ = new Date(detail.enterEndDate);
          }
        })
      }else{
        articleDetailData.siteSelect.push({
          key: Date.now(),
          siteIdArr: [],
        })
      }
    },
    data() {
      let validatePeopleAmount = (rule, val, callback) => {
        let value = (val + '')
        if (value == '') {
          callback();
        } else {
          let reg = /(^0$|^[1-9]{1}[0-9]*$)/g;
          if (!reg.test(value)) {
            callback("请输入正确的数字");
          }
          callback();
        }
      };
      let validateActivityStartTime = (rule, val, callback) => {
          if(val === '') {
              callback('请选择活动开始时间')
          }else{
             let currentTime = new Date();
             if(val < currentTime) {
               callback('活动开始时间不能早于当前时间');
             }
             if(this.articleDetailData.activityEndDate_ && val > this.articleDetailData.activityEndDate_) {
               callback('活动开始时间不能晚于结束时间');
             }
            callback()
          }
      };
      let validateActivityEndTime = (rule, val, callback) => {
        if(val === '') {
          callback('请选择活动结束时间')
        }else{
          let currentTime = new Date();
          if(val < currentTime) {
            callback('活动结束时间不能早于当前时间');
          }
          if(this.articleDetailData.activityStartDate_ && val < this.articleDetailData.activityStartDate_) {
            callback('活动结束时间不能早于开始时间');
          }
          callback()
        }
      };
      let validateEnterStartTime = (rule, val, callback) => {
        if(val === '') {
          callback('请选择报名开始时间')
        }else{
          let currentTime = new Date();
          if(val < currentTime) {
            callback('报名开始时间不能早于当前时间');
          }
          if(this.articleDetailData.enterEndDate_ && val > this.articleDetailData.enterEndDate_) {
            callback('报名开始时间不能晚于结束时间');
          }
          callback()
        }
      };
      let validateEnterEndTime = (rule, val, callback) => {
        if(val === '') {
          callback('请选择报名结束时间')
        }else{
          let currentTime = new Date();
          if(val < currentTime) {
            callback('报名结束时间不能早于当前时间');
          }
          if(this.articleDetailData.enterStartDate_ && val < this.articleDetailData.enterStartDate_) {
            callback('报名结束时间不能早于开始时间');
          }
          if(this.articleDetailData.activityEndDate_ && val > this.articleDetailData.activityEndDate_){
            callback('报名结束时间不能晚于活动结束时间');
          }
          callback()
        }
      };
      return {
        dataSource: '',
        isFirstEnter: true,
        activityId: '',
        options: {
          value: 'id',
          label:'name',
          children: 'children'
        },
        cityData:[],
        provinceData: [],
        fullscreenLoading: false,
        supportFile: ['.jpeg', '.jpg', '.png', '.gif'],
        isSubmit: false,
        categoryIsDisabled: false,
        breadcrumbData: {
          list: [
            {
              name: '运营',
              path: null,
              clickAble: false
            },{
              name: '活动管理',
              path: '/operationMgt/activityMgt',
              clickAble: true
            }, {
              name: '发起活动',
              path: null,
              clickAble: false
            }
          ],
          returnData: {
            isReturn: true, path: null
          },
          iconName: 'operation-icon',
        },
        articleDetailData: {
          id: "",
          activityEndDate: '',
          activityStartDate: '',
          cityId: '',
          content: '',
          detailAddress: '',
          enterEndDate: '',
          enterStartDate: '',
          imageIds: '',
          limitPeopleAmount: 0,
          published: '',
          siteIds: '',
          sponsor: '',
          title: '',

          provinceId: '',
          enterEndDate_: '',
          enterStartDate_: '',
          activityEndDate_: '',
          activityStartDate_: '',
          enterType:'Default',
          siteSelect: [],
        },
        imageUrl: '',
        coverId: '',
        positionCheckList: [],
        positionOptions: ['热点资讯', '社区公告', '活动入口'],
        submitFormRules: {
          activityStartDate_:{validator: validateActivityStartTime, trigger: 'change'},
          activityEndDate_:{validator: validateActivityEndTime, trigger: 'change'},
          enterEndDate_:{validator: validateEnterEndTime, trigger: 'change'},
          enterStartDate_:{validator: validateEnterStartTime, trigger: 'change'},
          cityId: {type:'number',required:true,message:'请选择城市',change:'trigger'},
          detailAddress:[{required:true,message:'请输入详细地址',trigger:'change'},{max:100,message:'不超过100个字符',trigger:'change'}],
          provinceId:{type:'number',required:true,message:"请选择省份",trigger:'change'},
          limitPeopleAmount: {validator: validatePeopleAmount, trigger: 'change'},
          sponsor:[{min:0,max:100,message:'不超过100个字符',trigger:'change'}],
          title: [
            {required: true, message: "请输入标题", trigger: 'change'},
            {max: 30, message: '不超过30个字符', trigger: 'change'},
            {min: 5, message: '不少于5个字符', trigger: 'change'}
          ],
          source: [
            {required: true, message: "请输入来源", trigger: 'change'},
            {max: 8, message: '不超过8个字符', trigger: 'change'}
          ],
          content: {required: true,message:'请输入活动内容', trigger: 'change'},
          imageIds: {required: true, message: '请上传图片'},
        },
      }
    }
  }
</script>

<style lang="less">
  @import '../../../assets/style/main.less';

  .MkAddActivity {
    .addNode{
      display:inline;
      cursor:pointer;
      color: @creatButton;
      i{
        color:@creatButton;
      }
      &:hover{
        .my-opacity();
      }
    }
    .add-article-content-box {
      padding: 30px;
      background-color: #fff;
    }
    .top-form .el-form-item {
      width: 600px;
    }

    .avatar-uploader .el-upload {
      border: 1px dashed #d9d9d9;
      border-radius: 6px;
      cursor: pointer;
      position: relative;
      overflow: hidden;
    }
    .avatar-uploader .el-upload:hover {
      border-color: @primaryColor;
    }
    .avatar-uploader-icon {
      font-size: 28px;
      color: #8c939d;
      width: 178px;
      height: 178px;
      line-height: 178px;
      text-align: center;
    }
    .avatar {
      width: 178px;
      height: 178px;
      display: block;
    }

    .ensure-save-box {
      background-color: @primaryColor;
      padding: 30px 40px;
      .color1 {
        color: @primaryColor;
      }
      .color2 {
        color: @creatButton;
      }
      .btnStyle {
        min-width: 120px;
        display: inline-block;
        height: 40px;
        background-color: #fff;
        text-align: center;
        line-height: 40px;
        border-radius: 5px;
        margin-right: 60px;
        cursor: pointer;
        font-size: 14px;
      }
    }
  }

  .ql-container .ql-editor {
    min-height: 320px;
    padding-bottom: 16px;
    max-height: 400px;
  }

  .ckeditor-content-size {
    width: 800px !important;
  }
</style>
